<template>
	<view class="container">
		<uni-nav-bar left-icon="back" status-bar :fixed="true" :border="false" title="设备信息"
			backgroundColor="#0081ff" color="white" @clickLeft="goBack" size="24">
		</uni-nav-bar>
		<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" activeColor="#0081ff"
			styleType="text" class="segment-tabs"></uni-segmented-control>
		<view class="content">
			<view v-show="current === 0">
				<view :class="['read_btns','nodiag']">
					<view class="cacel_btn" @click="cancleConnect">
						断开连接
					</view>
					<view class="scan_left">
						<view type="default" class="grades">{{GRADE}}
							<span>分</span>
						</view>
						<view class="scan-text" v-if="!isProcess">
							<h4 class="scaning">点击一键诊断
								<button class="read_btn" v-if="!isProcess&&isDiagnosis" @click="isRead">一键诊断</button>
								<button v-if="isProcess" class="read_btn">诊断中...</button>
							</h4>
							<text>获取设备监控、网络、软件等状态信息哦~</text>
						</view>
						<view class="scan-text" v-else>
							<h4 class="scaning">智能扫描中</h4>
							<text>正在诊断监控项~</text>
						</view>
					</view>


					<view class="progress-box" v-if="isProcess">
						<progress :percent="percent" :border-radius="20" show-info active="true" active-mode="forwards"
							:stroke-width="8" backgroundColor="#ffffff" activeColor="#58a1e8" />
					</view>
				</view>
				<view class="diognosis-btns">
					<u-button v-if="!isDiagnosis" class="dg-btn" @click="isRead">一键诊断</u-button>
				</view>
				<view v-if="isDiagnosis">
					<view class="cards param-content" id="poster">
						<u-collapse :accordion="false">
							<u-collapse-item title="系统开关量" :open="true" class="collapse-one" :disabled="statusResult">
								<view v-if="statusResult" :style="{color: comColor(0)}">
									读取失败
								</view>
								<u-cell-group :border="false" v-else>
									<u-cell-item title="摄像头是否在线:" :arrow="false"
										:value="CAMERA_ONLINE[masterControl.param1] || masterControl.param1"
										:value-style="{color: comColor2(masterControl.param1)}">
									</u-cell-item>
									<u-cell-item title="4G是否在线 :" :arrow="false"
										:value="CAMERA_ONLINE[masterControl.param2] || masterControl.param2"
										:value-style="{color: comColor2(masterControl.param2)}">
									</u-cell-item>
								</u-cell-group>
							</u-collapse-item>
							<u-collapse-item title="信号质量" :open="true" class="collapse-one" v-if="isShow>0">
								<u-cell-item title="信号值质量:" :arrow="false" :value="masterControl.param4">
								</u-cell-item>
							</u-collapse-item>

							<u-collapse-item title="硬件" :open="true" class="collapse-one" v-if="isShow>1">
								<u-cell-item title="仓控板得分率:" :arrow="false" :value="`${masterControl.param5}%`">
								</u-cell-item>
								<u-cell-item title="充电电源（输出继电器）得分率:" :arrow="false" :value="`${masterControl.param6}%`">
								</u-cell-item>
								<u-cell-item title="电子锁状态得分率:" :arrow="false" :value="`${masterControl.param7}%`">
								</u-cell-item>
								<u-cell-item title="格口温度得分率:" :arrow="false" :value="`${masterControl.param8}%`">
								</u-cell-item>
								<u-cell-item title="电表状态:" :arrow="false"
									:value="COMMUNITE_ONLINE[masterControl.param3] || masterControl.param3"
									:value-style="{color: comColor2(masterControl.param3)}">
								</u-cell-item>
							</u-collapse-item>
							<u-collapse-item title="综合" :open="true" class="collapse-one" v-if="isShow>2">
								<u-cell-item title="柜体温度得分率:" :arrow="false" :value="`${masterControl.param9}%`">
								</u-cell-item>
								<u-cell-item title="本地仓启用率:" :arrow="false" :value="`${masterControl.param10}%`">
								</u-cell-item>
								<u-cell-item title="设备利用率:" :arrow="false" :value="`${masterControl.param11}%`">
								</u-cell-item>
							</u-collapse-item>
							<u-collapse-item title="软件" :open="true" class="collapse-one" v-if="isShow>3">
								<u-cell-item title="主控版本:" :arrow="false" value="是最新版本"
									:value-style="{color: comColor(1)}">
								</u-cell-item>
								<u-cell-item title="柜控版本:" :arrow="false" value="是最新版本"
									:value-style="{color: comColor(1)}">
								</u-cell-item>
								<u-cell-item title="充电电源(充电板)版本:" :arrow="false" value="是最新版本"
									:value-style="{color: comColor(1)}">
								</u-cell-item>
							</u-collapse-item>
						</u-collapse>
					</view>
				</view>

			</view>
			<view v-show="current === 1 || current === 2 ">
				<view class="param-contents">
					<u-card v-for="(one ,index) in paramItems" :key="index" :title="one"
						@click="goPage(index)"></u-card>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		ab2hex,
		hexCharCodeToStr,
		doCopy,
		calculateCRC16,
		strLength,
		sendAuthString,
	} from "@/utils/index.js";
	import {
		base64ToPath
	} from 'image-tools';
	import {
		mapState,
	} from 'vuex';
	import {
		getLockOption,
		batteryIsOn,

		NETWORK,
		PLATFORM_CONNECT,
		IS_ENABLE,
		IS_ONLINE,
		POWER_CHANGE,
		IS_WARN,
		IS_ENABLED,
		HEAT1,
		ABNORMAL_OUTAGE,
		FLOODLIGHT,
		MAINTAIN_DOOR,
		WATER_FEEDBACK,
		SMOKE_STATUS,
		IS_START,
		IS_FAULT,
		IS_NORMAL,
		OVETRCURRENT,
		IS_DORMANT,
		CURRENT_LIMIT,
		IS_AUTO,
		IS_FORBIDDEN,
		BATERRY_TYPE,
		RUN_STATUS,
		UNDERVOL,
		UPVOL,
		HIGHTEM,
		PRESSURE,
		MOS_STATUS,
		BMS_STATUS,
		IS_DOORS,
		IS_CHARGE,
		CHARGE_CURRENT,
		OVER_CURRENT,
		VOL_LOSE,
		NOTALLOW_CHARGE,
		BATTERY_ONLINE,
		LOAD_PROTECT,
		UP_VOL_PROTECT,
		CURRENT_LIMIT_WARN,
		CELL_HIGH_TEM,
		ENVIR_LOW_TEM,
		ENVIR_HIGH_TEM,
		MOS_HIGH_TEM,
		LOW_VOL_PROTECT,
		INVERSE_PROTECT,
		BMS_SIGN,
		MOS_PIPE_STATUS,
		BATTERY_ADJUST,
		BATTERY_STATUSING,
		BATTERY_CONTROL,
		DOOR_STATUS,
		BATTERY_ISON,
		CAMERA_ONLINE,
		COMMUNITE_ONLINE,
	} from "@/common/config.js";

	import detectjs from "./detect.js";
	import {
		authPassword,
		serviceId,
		characteristicId1,
		characteristicId2,
	} from "@/utils/service.js"
	export default {
		mixins: [detectjs],
		data() {
			return {
				isShow: 0,
				statusResult: '',

				show: false,
				device: null,
				deviceInfo: {},

				deviceType: null, //设备类型
				binNum: 0, //仓数

				getLockOption: getLockOption,
				batteryIsOn: batteryIsOn,

				NETWORK: NETWORK,
				PLATFORM_CONNECT: PLATFORM_CONNECT,
				IS_ENABLE: IS_ENABLE,
				IS_ONLINE: IS_ONLINE,
				POWER_CHANGE: POWER_CHANGE,
				IS_WARN: IS_WARN,
				IS_ENABLED: IS_ENABLED,
				HEAT1: HEAT1,
				ABNORMAL_OUTAGE: ABNORMAL_OUTAGE,
				FLOODLIGHT: FLOODLIGHT,
				MAINTAIN_DOOR: MAINTAIN_DOOR,
				WATER_FEEDBACK: WATER_FEEDBACK,
				SMOKE_STATUS: SMOKE_STATUS,
				IS_START: IS_START,
				IS_FAULT: IS_FAULT,
				IS_NORMAL: IS_NORMAL,
				OVETRCURRENT: OVETRCURRENT,
				IS_DORMANT: IS_DORMANT,
				CURRENT_LIMIT: CURRENT_LIMIT,
				IS_AUTO: IS_AUTO,
				IS_FORBIDDEN: IS_FORBIDDEN,
				BATERRY_TYPE: BATERRY_TYPE,
				RUN_STATUS: RUN_STATUS,
				UNDERVOL: UNDERVOL,
				UPVOL: UPVOL,
				HIGHTEM: HIGHTEM,
				PRESSURE: PRESSURE,
				MOS_STATUS: MOS_STATUS,
				BMS_STATUS: BMS_STATUS,
				IS_DOORS: IS_DOORS,
				IS_CHARGE: IS_CHARGE,
				CHARGE_CURRENT: CHARGE_CURRENT,
				OVER_CURRENT: OVER_CURRENT,
				VOL_LOSE: VOL_LOSE,
				NOTALLOW_CHARGE: NOTALLOW_CHARGE,
				BATTERY_ONLINE: BATTERY_ONLINE,
				LOAD_PROTECT: LOAD_PROTECT,
				UP_VOL_PROTECT: UP_VOL_PROTECT,
				CURRENT_LIMIT_WARN: CURRENT_LIMIT_WARN,
				CELL_HIGH_TEM: CELL_HIGH_TEM,
				ENVIR_LOW_TEM: ENVIR_LOW_TEM,
				ENVIR_HIGH_TEM: ENVIR_HIGH_TEM,
				MOS_HIGH_TEM: MOS_HIGH_TEM,
				LOW_VOL_PROTECT: LOW_VOL_PROTECT,
				INVERSE_PROTECT: INVERSE_PROTECT,
				BMS_SIGN: BMS_SIGN,
				MOS_PIPE_STATUS: MOS_PIPE_STATUS,
				BATTERY_ADJUST: BATTERY_ADJUST,
				BATTERY_STATUSING: BATTERY_STATUSING,
				BATTERY_CONTROL: BATTERY_CONTROL,
				DOOR_STATUS: DOOR_STATUS,
				BATTERY_ISON: BATTERY_ISON,
				CAMERA_ONLINE: CAMERA_ONLINE,
				COMMUNITE_ONLINE: COMMUNITE_ONLINE,

				// '控制'
				items: ['诊断', '参数', '版本查询'],
				current: 0,
				params: "",

				exportBtn: {
					width: '90%',
					position: "fixed",
					left: '5%',
					bottom: "140rpx",
				},
				percent: 10, //百分比0~100

				isDiagnosis: false, //诊断状态
				currentIndex: null, //当前仓号
				paramItems: [
					"主控单元", "仓控单元", "检测单元",
				], //参数模块

				command: 8, //命令字
				currentCollapse: 0, //当前折叠面板
				isProcess: false, //是否诊断中
				dgMessage: "", //检测状态提示信息

				masterControl: { //主控状态
					param1: '',
					param2: '',
					param3: '',
					param4: '',
					param5: '',
					param6: '',
					param7: '',
					param8: '',
					param9: '',
					param10: '',
					param11: '',
				},
				GRADE:100,//分值
			}
		},
		async onLoad(e) {
			this.deviceInfo = JSON.parse(decodeURIComponent(e.deviceInfo));
			// 设备类型 CC:充电柜; CHZD:换电柜
			this.deviceType = (this.deviceInfo.localName && this.deviceInfo.localName.startsWith('CC') || this
					.deviceInfo.name && this.deviceInfo.name.startsWith('CC')) ?
				"CC" : 'CHZD';
			// 计算仓数
			this.binNum = this.computBInNum(this.deviceInfo.localName);

			// 监听之前是否有其他设备连接,是,断开连接,建立新连接;否,直接建立连接.
			// 若当前设备已连接连接,则不做操作
			if (this.curConnectBLE.length == 0) {
				try {
					this.$Toast.loading('连接中~');
					await this.connect(this.deviceInfo);
					await this.doAuth();

					//协商MTU
					this.setMaxMTU(this.deviceInfo.deviceId);
				} catch (err) {
					console.log(err)
					// 测试
					// setTimeout(() => {
					// 	this.goBack();
					// }, 2000)

				}
			} else {
				let inx = this.curConnectBLE.findIndex(item => item.deviceId == this.deviceInfo.deviceId);
				if (inx == -1) {
					let datas = await this.$store.dispatch('closeBLEConnection', this.curConnectBLE[0].deviceId);
					if (datas) {
						this.$Toast.loading('连接中~');
						try {
							await this.connect(this.deviceInfo);
							await this.doAuth();

							// Android协商MTU
							this.setMaxMTU(this.deviceInfo.deviceId);
						} catch (err) {
							// 测试
							// setTimeout(() => {
							// 	this.goBack();
							// }, 2000)
						}
					}
				}
			}
		},
		computed: {
			...mapState(['curConnectBLE', 'maxMTU']),
			// 柜控电源数量
			comCabinNum() {
				if (Number(this.binNum) < 24) {
					return 1;
				} else if (Number(this.binNum) >= 24 && Number(this.binNum) < 36) {
					return 2;
				} else {
					return 3;
				}
			},
			comColor() {
				return function(item) {
					if (item == 0) {
						return '#f56c6c';
					} else if (item == 1) {
						return '#19be6b'
					}
				}
			},
			comColor2() {
				return function(item) {
					if (item == 1) {
						return '#f56c6c';
					} else if (item == 0) {
						return '#19be6b'
					}
				}
			},
			detailYesOrNo() {
				return function(val) {
					if (val == 1) {
						return "是";
					} else if (val !== '' && val != 1) {
						return '否';
					} else {
						return '';
					}
				}
			},
		},
		watch: {
			'$store.state.curConnectBLE': {
				immediate: true,
				deep: true,
				handler(e) {},
			},
			'maxMTU': {
				immediate: true,
				deep: true,
				handler(e) {
					console.log('watch maxMTU值变化')
					console.log(e)
				},
			}
		},
		methods: {
			// 连接设备
			async connect(item) {
				try {
					await this.$store.dispatch('createBLEConnection', item)
					console.log({
						deviceId: item.deviceId,
						serviceId,
						characteristicId: characteristicId2
					})
					await this.$store.dispatch('checkDeviceService', {
						deviceId: item.deviceId,
						serviceId,
						characteristicId: characteristicId2
					})
					item.serviceId = serviceId
					item.characteristicId = characteristicId2
					this.deviceInfo = item
				} catch (err) {}
			},
			// 鉴权请求
			doAuth() {
				let that = this;
				// that.$Toast.loading('鉴权中~');
				// 向蓝牙设备发送数据
				let {
					deviceId,
				} = that.deviceInfo;
				const buffer = sendAuthString(authPassword);
				uni.writeBLECharacteristicValue({
					deviceId,
					serviceId,
					characteristicId: characteristicId1,
					// 这里的value是ArrayBuffer类型
					value: buffer,
					success(res) {
						console.log('writeBLECharacteristicValue success', res.errMsg)
						console.log(res)
						console.log(res.errMsg)
						that.doAuthRead();
					},
					fail(err) {
						console.log(err)
						that.$Toast.none('鉴权失败！');
						// 测试
						// setTimeout(() => {
						// 	that.goBack();
						// }, 2000)
					}
				})
			},
			doAuthRead() {
				let {
					deviceId,
				} = this.deviceInfo;
				let that = this;
				// 读取低功耗蓝牙设备的特征值的二进制数据值
				uni.readBLECharacteristicValue({
					deviceId,
					serviceId,
					characteristicId: characteristicId1,
					success(res) {
						uni.onBLECharacteristicValueChange(function(res) {
							// console.log(
							// 	`characteristic ${res.characteristicId} has changed, now is ${res.value}`
							// )
							let value = res.value;
							console.log(value)
							// 第1字节为鉴权结果，后面6字节为毫秒时间戳，鉴权失败时时间戳返回为0
							let uint8Array = new Uint8Array(value);
							let newArray = Array.from(uint8Array);

							let start = newArray.slice(0, 1);
							let end = newArray.slice(1);
							if (start == 1) {
								that.$Toast.none('鉴权失败！');
								// setTimeout(() => {
								// 	that.goBack();
								// }, 2000)
							} else if (start == 0) {
								that.$Toast.success('鉴权成功！');
							}
						})

					},
					fail(fal) {
						console.log("读取数据数据失败", fal)
						that.$Toast.none('鉴权失败！');
						// 测试
						// setTimeout(() => {
						// 	that.goBack();
						// }, 2000)
					}
				})
			},

			onClickItem(e) {
				if (this.current != e.currentIndex) {
					this.current = e.currentIndex;
				}
			},
			getValue(cpcl) {
				let characteristicValue = ab2hex(cpcl);
				let strValue = hexCharCodeToStr(characteristicValue)
				return strValue;
			},

			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 断开连接
			async cancleConnect() {
				let res = await this.$store.dispatch('closeBLEConnection', this.deviceInfo.deviceId);
				// 断开成功,返回上一页
				if (res) {
					this.$Toast.none('连接已断开~');
					setTimeout(() => {
						this.goBack();
					}, 2000)
				}
			},
			// 协商MTU
			setMaxMTU(deviceId) {
				let that = this;
				let platform = uni.getSystemInfoSync().platform;
				switch (platform) {
					case "android":
						uni.setBLEMTU({
							deviceId: deviceId,
							mtu: 512,
							success(res) {
								console.log("设置最大值成功========")
								console.log(res)
							}
						})
						// 若设置失败,会分配一个合适的MTU
						uni.onBLEMTUChange(function(res) {
							console.log('bluetooth mtu is::::::::', res.mtu)
							console.log(res)
							that.$store.commit("setMaxMTU", res.mtu);
						})
						break;
					case "ios":
						uni.getBLEMTU({
							deviceId: deviceId,
							success: res => {
								console.log(res)
								that.$store.commit("setMaxMTU", res.mtu);
							},
							fail: err => {
								console.log('获取MTU失败:', err);
							}
						});
						break;
				}
			},
			// 计算仓数
			computBInNum(str) {
				const regex = /\d/;
				const match = str.match(regex);
				if (match) {
					const index = match.index;
					const result = str.substr(index, 2);
					return result;
				}
			},

			// 参数详情
			goPage(index) {
				let url = this.current == 1 ? `/pagesA/charge/param/param` : `/pagesA/charge/version/index`;
				uni.navigateTo({
					url: `${url}?type=${index}&binNum=${this.binNum}&deviceInfo=${encodeURIComponent(JSON.stringify(this.deviceInfo))}`
				})
			},
		}
	}
</script>
<style>
	page {
		background-color: #EFF0F1 !important;
	}
</style>
<style lang="scss" scoped>
	@import "@/static/iconfont.css";
	@import "@/pagesA/bluetooth/index.scss";
</style>